<template>
  <div class="content">
    <el-table
      highlight-current-row
      :data="dataList"
      @cell-dblclick="handleClick"
    >
      <el-table-column prop="songName" label="歌曲" />
      <el-table-column prop="singerName" label="歌手" />
      <el-table-column prop="introduction" label="专辑" />
      <el-table-column label="编辑" width="80" align="center">
        <template #default="scope">
          <el-dropdown>
            <el-icon><MoreFilled /></el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  :icon="Download"
                  @click="
                    downloadMusic({
                      songUrl: scope.row.url,
                      songName: scope.row.name,
                    })
                  "
                  >下载</el-dropdown-item
                >
                <el-dropdown-item
                  :icon="Delete"
                  v-if="showDelete"
                  @click="deleteCollection({ id: scope.row.id })"
                  >{{ isFav ? "取消收藏" : "删除" }}</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="token"
                  :icon="Star"
                  @click="setSongId(scope.row.id)"
                  >添加到歌单</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 选择框 -->
    <div class="add" v-show="showAdd">
      <el-select v-model="value" class="m-2" placeholder="Select">
        <el-option
          v-for="item in state.options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button @click="addSong">增加</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  getCurrentInstance,
  toRefs,
  computed,
  reactive,
  ref,
  onMounted,
} from "vue";
import { useStore } from "vuex";
import mixin from "@/mixins/mixin";
import { MoreFilled, Delete, Download, Star } from "@element-plus/icons-vue";
import { HttpManager } from "@/api";
import { Icon } from "@/enums";

export default defineComponent({
  components: {
    MoreFilled,
  },
  props: {
    songList: Array,
    show: {
      //代表是否是搜索歌单
      default: false,
    },
    isFav: {
      default: false,
    },
  },
  emits: ["changeData"],
  setup(props) {
    const {
      getSongTitle,
      getSingerName,
      playMusic,
      checkStatus,
      downloadMusic,
    } = mixin();
    const { proxy } = getCurrentInstance();
    const store = useStore();
    const { songList, show, isFav } = toRefs(props);
    const userList = ref([]); //用户创建的歌单列表
    const value = ref("");
    const showAdd = ref(false);

    const iconList = reactive({
      dislike: Icon.Dislike,
      like: Icon.Like,
    });

    const songUrl = computed(() => store.getters.songUrl);
    const singerName = computed(() => store.getters.singerName);
    const songTitle = computed(() => store.getters.songTitle);
    const token = computed(() => store.getters.token);
    const selectId = ref(""); //选中的歌曲id

    //是否显示删除选项
    const showDelete = computed(() => {
      for (let i = 0; i < userList.value.length; i++) {
        if (userList.value[i].id == proxy.$store.getters.songDetails.id)
          return show && checkStatus();
      }
      return false && checkStatus();
    });
    //记录当前歌单信息
    const state = reactive({
      options: [],
    });
    const dataList = computed(() => {
      //便利各个songlist代理中的歌曲信息，获取存有歌曲信息的数组
      const list = [];
      songList.value.forEach((item: any, index) => {
        item["songName"] = getSongTitle(item.name);
        item["singerName"] = getSingerName(item.name);
        item["index"] = index;
        list.push(item);
      });
      return list;
    });

    //获取当前用户的歌单列表
    async function getUserSongList(value) {
      if (!value) return;
      const result = (await HttpManager.getUserSongList(value)) as ResponseBody;
      userList.value = result.data;
      let results = [];
      for (let i = 0; i < userList.value.length; i++) {
        results.push({
          label: userList.value[i].title,
          value: userList.value[i].id,
        });
      }
      state.options = results;
    }

    onMounted(() => {
      // getSearchList(proxy.$route.query.keywords);
      getUserSongList(proxy.$store.getters.userId);
    });

    //点击之后播放音乐
    function handleClick(row) {
      console.log(row);
      playMusic({
        id: row.id,
        url: row.url,
        pic: row.pic,
        index: row.index,
        name: row.name,
        lyric: row.lyric,
        currentSongList: songList.value,
      });
    }

    const userId = computed(() => store.getters.userId);

    //在用户收藏列表，如果点击删除，则发送请求，将该对应信息删除
    async function deleteCollection({ id }) {
      // if (!checkStatus()) return;
      if (isFav.value) {
        console.log("删除收藏中的歌曲");
        const result = (await HttpManager.deleteCollection(
          userId.value,
          id
        )) as ResponseBody;
        (proxy as any).$message({
          message: result.message,
          type: result.type,
        });
        if (result.type === "success") proxy.$emit("changeData");
      } else {
        console.log("删除歌单中的歌曲");
        const result = (await HttpManager.deleteListSong(
          proxy.$store.getters.songDetails.id,
          id
        )) as ResponseBody;
        (proxy as any).$message({
          message: result.message,
          type: result.type,
        });
        if (result.type === "success") {
          proxy.$emit("changeData");
        }
      }
    }

    //添加到歌单
    function setSongId(id) {
      selectId.value = String(id);
      showAdd.value = true;
    }

    async function addSong() {
      if (selectId.value == "") {
        (proxy as any).$message({
          message: "请选择歌曲",
        });
        showAdd.value = false;
        return;
      }
      if (value.value == "") {
        (proxy as any).$message({
          message: "请选择歌单",
        });
        showAdd.value = false;
        return;
      }
      const params = new URLSearchParams();
      params.append("songId", selectId.value);
      params.append("songListId", value.value);
      console.log(selectId.value, value.value);
      const result = (await HttpManager.addToSongList(params)) as ResponseBody;
      (proxy as any).$message({
        message: result.message,
        type: result.type,
      });
      showAdd.value = false;
    }

    return {
      showAdd,
      state,
      value,
      dataList,
      iconList,
      token,
      Delete,
      Download,
      Star,
      songUrl,
      singerName,
      songTitle,
      showDelete,
      handleClick,
      downloadMusic,
      deleteCollection,
      setSongId,
      addSong,
    };
  },
});
</script>

<style lang="scss" scoped>
@import "@/assets/css/var.scss";
@import "@/assets/css/global.scss";

.content {
  background-color: $color-white;
  border-radius: $border-radius-songlist;
  padding: 10px;
}

.content:deep(.el-table__row.current-row) {
  color: $color-black;
  font-weight: bold;
}

.content:deep(.el-table__row) {
  cursor: pointer;
}

.icon {
  @include icon(1.2em, $color-black);
}
</style>
